package cn.hubujyjs.mooc.service.impl;

import cn.hubujyjs.mooc.entity.Subject;
import cn.hubujyjs.mooc.mapper.SubjectMapper;
import cn.hubujyjs.mooc.service.SubjectService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Huang Jintao
 * @since 2022-11-15
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    public static final String MOOC_SUBJECT_CACHE="mooc:subject:cache:";
    @Override
    @Transactional
    public List<Subject> listSubject() {
        String s = redisTemplate.opsForValue().get(MOOC_SUBJECT_CACHE);
        if (StrUtil.isNotEmpty(s)){
            return JSONUtil.toList(s, Subject.class);
        }
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Subject::getSort);
        List<Subject> list = this.list(wrapper);
        String jsonList = JSONUtil.toJsonStr(list);
        redisTemplate.opsForValue().set(MOOC_SUBJECT_CACHE,jsonList);
        return list;
    }
}
